<template>
	<div class="qr-container">
		<img v-if="imgUrl" :src="imgUrl" :style="{ width: `${size}px` }" alt="QR Code" />
		<slot name="controls"></slot>
	</div>
</template>
<script setup>
	import { onMounted, ref } from 'vue'
	import QRCode from 'qrcode'

	const props = defineProps({
		text: { type: String, required: true },
		size: { type: Number, default: 200 },
		logoSize: { type: Number, default: 0.2 },
		logoPath: { type: String, default: '/img/logo_32x32.png' },
		darkColor: { type: String, default: '#000000' },
		lightColor: { type: String, default: '#ffffff' }
	})

	const emit = defineEmits(['generated', 'error'])
	const imgUrl = ref('')

	const generate = async () => {
		console.log(11)
		try {
			const qrCanvas = document.createElement('canvas')
			await QRCode.toCanvas(qrCanvas, props.text, {
				width: props.size,
				margin: 2,
				color: { dark: props.darkColor, light: props.lightColor }
			})

			if (props.logoPath) {
				const logoImg = new Image()
				logoImg.src = props.logoPath
				await new Promise((resolve, reject) => {
					logoImg.onload = resolve
					logoImg.onerror = () => reject(new Error('Logo加载失败'))
				})

				const ctx = qrCanvas.getContext('2d')
				const logoWidth = qrCanvas.width * props.logoSize
				const logoX = (qrCanvas.width - logoWidth) / 2
				const logoY = (qrCanvas.height - logoWidth) / 2

				ctx.fillStyle = props.lightColor
				ctx.roundRect(logoX - 2, logoY - 2, logoWidth + 4, logoWidth + 4, 8)
				ctx.fill()
				ctx.drawImage(logoImg, logoX, logoY, logoWidth, logoWidth)
			}
			imgUrl.value = qrCanvas.toDataURL('image/png')
			emit('generated', imgUrl.value)
		} catch (err) {
			console.error('生成失败:', err)
			emit('error', err)
		}
	}
	onMounted(() => {
		generate()
	})
</script>

<style scoped>
	.qr-container {
		display: inline-block;
		padding: 10px;
		background: white;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}
</style>
